﻿using System;
using System.Collections.Generic;
using System.Text;

namespace SStateMachine
{
    public partial class StateMachine<TState, TTrigger>
    {
        public class StateEvents
        {
            private readonly TState state;
            private readonly Dictionary<TTrigger, Transition> triggers = new Dictionary<TTrigger, Transition>();
            private readonly List<Action> OnEnterEvents = new List<Action>();
            private readonly List<Action> OnExitEvents = new List<Action>();

            public TState State => state;

            public StateEvents(TState state)
            {
                this.state = state;
            }

            public void AddEnterEvent(Action action)
            {
                OnEnterEvents.Add(action);
            }

            public void AddExitEvent(Action action)
            {
                OnExitEvents.Add(action);
            }

            // If transition is not exist, return true. Or return false.
            public void AddTrigger(TTrigger trigger, TState destination)
            {
                if (triggers.ContainsKey(trigger))
                {
                    triggers[trigger] = new Transition(state, destination);
                }
                else
                {
                    triggers.Add(trigger, new Transition(state, destination));
                }
            }

            public Transition GetTransition(TTrigger trigger)
            {
                return triggers[trigger];
            }

            public void Enter()
            {
                foreach (var enterAction in OnEnterEvents)
                    enterAction?.Invoke();
            }

            public void Exit(TTrigger trigger)
            {
                if (!triggers.ContainsKey(trigger))
                    throw new KeyNotFoundException();

                foreach (var exitAction in OnExitEvents)
                    exitAction?.Invoke();
            }
        }
    }
}
